package com.etoak.car.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Service
public class LikeService{

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    public long getLikeCount(String key) {
        //hlen
        return stringRedisTemplate.opsForHash().size(key);
    }


    public Map<String,Object> like(String key, String username) {
        Map<String,Object> result = new HashMap<>();

        //如果用户点赞就取消点赞
        if(stringRedisTemplate.opsForHash().hasKey(key,username)){
            stringRedisTemplate.opsForHash().delete(key,username);
            result.put("isLike",false);
        }else {
            stringRedisTemplate.opsForHash().put(key,username,"1");
            result.put("isLike",true);
        }
        //设置点赞凉
        result.put("count",this.getLikeCount(key));
        return result;
    }


    public Set<String> getLikeUser(String key) {
        Set<String> result = new HashSet<>();
        stringRedisTemplate.opsForHash().keys(key).forEach(k->{
            result.add((String) k);
        });
        return result;
    }
}
